import {
	setStorage,
	getStorage
} from '@/utils/storage.js'
export default {
	namespaced: true,
	state: {
		// 每个商品的信息对象，都包含如下 6 个属性：
		// { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
		cart: getStorage('cartList') || []
	},
	getters: {
		total(state) {
			return state.cart.reduce((pre, item) => {
				return pre + item.goods_count
			}, 0)
		},
		checkedCount(state) {
			return state.cart.filter(item => item.goods_state === true).reduce((pre, item) => {
				return pre + item.goods_count
			}, 0)
		},
		setPrice(state) {
			return state.cart.filter(item => item.goods_state === true).reduce((pre, item) => {
				return pre + item.goods_price * item.goods_count
			}, 0).toFixed(2)
		}
	},
	mutations: {
		addGoods(state, goods) {
			const findGoods = state.cart.find(item => item.goods_id === goods.goods_id)
			if (findGoods) {
				findGoods.goods_count++
			} else {
				state.cart.push(goods)
			}
			setStorage('cartList', state.cart)
		},
		setGoodsState(state, goods) {
			const findRes = state.cart.find(item => item.goods_id === goods.goods_id)
			findRes.goods_state = !findRes.goods_state
			setStorage('cartList', state.cart)
		},
		changeNum(state, goods) {
			const findRes = state.cart.find(item => item.goods_id === goods.goods_id)
			findRes.goods_count = goods.goods_count
			setStorage('cartList', state.cart)
		},
		updateAllCart(state, flag) {
			state.cart.forEach(item => {
				item.goods_state = flag
				setStorage('cartList', state.cart)
			})
		},
		delGoods(state, payload) {
			state.cart = state.cart.filter(item => item.goods_id !== payload.goods_id)
			setStorage('cartList', state.cart)
		}
	}
}
